package com.demoworld;

import com.demoworld.dao.IUserDao;
import com.demoworld.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.util.UUID;

/**
 * Created by francis on 2017/6/14.
 */
public class main {
    @Test
    public void add() throws IOException {
        //配置文件的名称
        String resource = "mybatis-conf.xml";
        //通过Mybatis包中的Resources对象很轻松的获取到配置文件
        Reader reader = Resources.getResourceAsReader(resource);
        //通过SqlSessionFactoryBuilder创建
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //获得session实例
        SqlSession session = sqlSessionFactory.openSession();
        User user = new User();
        user.setId(UUID.randomUUID().toString());
        user.setName("francis");
        user.setSex("男");

        IUserDao mapper = session.getMapper(IUserDao.class);
        mapper.add(user);

        session.commit();
        session.close();
    }

    @Test
    public void testCalc() throws IOException {
        for (int i = 0; i <= 100; i++) {
            getById();
        }
    }

    @Test
    public void getById() throws IOException {
        //配置文件的名称
        String resource = "mybatis-conf.xml";
        //通过Mybatis包中的Resources对象很轻松的获取到配置文件
        Reader reader = Resources.getResourceAsReader(resource);
        //通过SqlSessionFactoryBuilder创建
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //获得session实例
        SqlSession session = sqlSessionFactory.openSession();

        IUserDao mapper = session.getMapper(IUserDao.class);
        User user = mapper.getById("fd671714-5ac5-4f87-9d34-0a7d73823662");
        System.out.println(user.getName());
        System.out.println(user.getSex());
        session.close();
    }

    @Test
    public void updateName() throws IOException {
        //配置文件的名称
        String resource = "mybatis-conf.xml";
        //通过Mybatis包中的Resources对象很轻松的获取到配置文件
        Reader reader = Resources.getResourceAsReader(resource);
        //通过SqlSessionFactoryBuilder创建
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //获得session实例
        SqlSession session = sqlSessionFactory.openSession();
        User user = new User();
        user.setId("fd671714-5ac5-4f87-9d34-0a7d73823662");
        user.setName("张三");

        IUserDao mapper = session.getMapper(IUserDao.class);
        mapper.updateName(user);

        session.commit();
        session.close();
    }
}
